package com.moxie.ocr.network;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MXGetRequestUtils {
    public static final String TAG = MXGetRequestUtils.class.getSimpleName();


    public static void getRequest(final String getUrl, final MXNetRequestCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getSynTest(getUrl,callback);
            }
        }).start();
    }

    public static void getSynTest(String url, final MXNetRequestCallback callback){
        try {
            if (url == null || "".equals(url)) {
                sendFailResult(callback, 404, "URL无效");
                return;
            }
            URL netURL=new URL(url);
            HttpURLConnection urlConn = (HttpURLConnection) netURL.openConnection();
            urlConn.setRequestMethod("GET");
            // 设置连接主机超时时间
            urlConn.setConnectTimeout(20 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(20 * 1000);
            // 设置是否使用缓存  默认是true
            urlConn.setUseCaches(true);
            urlConn.connect();
            if (urlConn.getResponseCode()==200){
                String result = streamToString(urlConn.getInputStream());
                sendSuccessResult(callback,result);
                Log.d("moxieNetwork","请求接口====="+result);
            }else {
                sendFailResult(callback,urlConn.getResponseCode(),"请求失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将输入流转换成字符串
     *
     * @param is 从网络获取的输入流
     * @return
     */
    public static String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
    }


    public static <T> void sendFailResult(final MXNetRequestCallback callback, final int errorCode, final String errorString) {
        if (callback != null) {
            callback.failed(errorCode, errorString);
        }
    }

    public static void sendSuccessResult(final MXNetRequestCallback callback, final String response) {

        if (callback != null) {
            callback.completed(response);
        }
    }


}
